<template>
  <div>
    <el-tabs type="border-card" :active-name="'spu'">
      <el-tab-pane name="spu" label="基本信息">
        <el-row>
          <el-form ref="addForm" :model="addData" :rules="addRules" size="medium" label-width="100px">
            <el-col :span="12">
              <el-form-item label="产品编码" prop="productCode">
                <el-input v-model="addData.productCode " placeholder="请输入产品编码" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="addData.productName " placeholder="请输入产品名称" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="搜索关键词" prop="keywords">
                <el-input v-model="addData.keywords " placeholder="请输入搜索关键词" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品类目" prop="catalogId">
                <el-select v-model="addData.catalogId" placeholder="请选择商品类目" clearable :style="{width: '100%'}">
                  <el-option
                    v-for="item in dataList"
                    :key="item.catalogName"
                    :label="item.catalogName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="批准文号" prop="approvalNumber">
                <el-input v-model="addData.approvalNumber " placeholder="请输入批准文号" clearable
                          :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="品牌" prop="brand">
                <el-input v-model="addData.brand" placeholder="请输入品牌" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="制造商" prop="manufacturer">
                <el-input v-model="addData.manufacturer " placeholder="请输入制造商" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="药品单位" prop="unit">
                <el-select v-model="addData.unit" placeholder="药品单位" clearable :style="{width: '100%'}">
                  <el-option v-for="(item, index) in unitOptions" :key="index" :label="item.key"
                             :value="item.key"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="处方类型" prop="prescriptionType">
                <el-select v-model="addData.prescriptionType" placeholder="请选择处方类型" clearable :style="{width: '100%'}">
                  <el-option v-for="(item, index) in prescriptionTypeOptions" :key="index" :label="item.key"
                             :value="item.key"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="外网链接" prop="outLink">
                <el-input v-model="addData.outLink " placeholder="请输入外网链接" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图片" prop="picture">
                <el-upload ref="upload" :file-list="picturefileList" :action="pictureAction"
                           :disabled="!hasPermission('perm')"
                           :before-upload="pictureBeforeUpload"
                           :on-success="handlePictureSuccess"
                           :on-remove="handleRemove"
                           list-type="picture"
                           accept="image/*">
                  <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="启用" prop="isDelete" required>
                <el-switch v-model="addData.isDelete"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="产品成分" prop="productmainmaterial">
                <el-input v-model="addData.productmainmaterial " type="textarea" placeholder="请输入产品成分"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="药物互相作用" prop="druginteractions">
                <el-input v-model="addData.druginteractions " type="textarea" placeholder="请输入药物互相作用"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="注意事项" prop="precautions">
                <el-input v-model="addData.precautions " type="textarea" placeholder="请输入注意事项"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="不良反应" prop="adverse">
                <el-input v-model="addData.adverse " type="textarea" placeholder="请输入不良反应"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="禁忌" prop="taboo">
                <el-input v-model="addData.taboo " type="textarea" placeholder="请输入禁忌"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-form>
          <el-col :span="24" align="right" class="saveBtn">
            <el-row>
              <el-button type="primary" icon="el-icon-goods" @click="saveProduct">保存商品</el-button>
              <el-button type="info" icon="el-icon-plus" :disabled="!(this.addData.id)" @click="addSku">添加库存</el-button>
            </el-row>
            <!--<el-button @click="dialogVisible = false">取 消</el-button>-->
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane name="sku" label="库存信息">

        <el-table :data="skus" border fit highlight-current-row style="width: 100%;">
          <el-table-column label="id" prop="id" align="center" width="100">
            <template slot-scope="{row}">
              <span>{{row.id}}</span>
            </template>
          </el-table-column>
          <el-table-column label="仓库名称" prop="stockId" align="center">
            <template slot-scope="{row}">
          <span>
            {{row.stockId | getStock}}
          </span>
            </template>
          </el-table-column>

          <el-table-column label="入库批次号" prop="batchNo" align="center" width="200">
            <template slot-scope="{row}">
              <span>{{row.batchNo}}</span>
            </template>
          </el-table-column>

          <el-table-column label="上架" prop="available" align="center" width="100">
            <template slot-scope="{row}">
              <span>{{row.available}}</span>
            </template>
          </el-table-column>

          <el-table-column label="供应商" prop="supplier" align="center" width="100">
            <template slot-scope="{row}">
              <span>{{row.supplier}}</span>
            </template>
          </el-table-column>

          <el-table-column label="含税成本" prop="cost" align="center" width="100">
            <template slot-scope="{row}">
              <span>{{row.cost}}</span>
            </template>
          </el-table-column>

          <el-table-column label="库存数量" prop="num" align="center" width="100">
            <template slot-scope="{row}">
              <span>{{row.num}}</span>
            </template>
          </el-table-column>

          <el-table-column label="库存单位" prop="unit" align="center" width="100">
            <template slot-scope="{row}">
              <span>{{row.unit}}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" prop="productDate" align="center" width="100">
            <template slot-scope="{row}">
              <span>{{row.productDate | format}}</span>
            </template>
          </el-table-column>
          <el-table-column label="过期时间" prop="expiredDate" align="center" width="100">
            <template slot-scope="{row}">
              <span>{{row.expiredDate | format}}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" prop="id" align="center">
            <template slot-scope="{row}">
              <el-button type="primary" @click="show(row)">编辑库存</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :page-size="params.pageSize"
          layout="prev, pager, next"
          :total="params.totalCount"
          @prev-click="searchSKU(-1)"
          @next-click="searchSKU(1)"
        ></el-pagination>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="title" :visible.sync="dialogVisible">
      <el-form ref="skuForm" :model="skuData" :rules="skuRules" size="medium" label-width="100px">
        <el-form-item label="仓库" prop="stockId">
          <el-select v-model="skuData.stockId" placeholder="请输入仓库" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in stocks" :key="index" :label="item.stockName"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入库批次号" prop="batchNo ">
          <el-input v-model="skuData.batchNo" placeholder="请输入入库批次号或系统自动生成" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="skuData.supplier" placeholder="请输入供应商" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="skuData.manufacturer" placeholder="生产厂家" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="含税成本" prop="cost">
          <el-input-number v-model="skuData.cost" placeholder="请输入含税成本" :precision="2" clearable
                           :style="{width: '100%'}"></el-input-number>
        </el-form-item>
        <el-form-item label="库存数量" prop="num">
          <el-input-number v-model="skuData.num" placeholder="库存数量" :step='1'></el-input-number>
        </el-form-item>
        <el-form-item label="库存单位" prop="unit">
          <el-select v-model="skuData.unit" placeholder="请选择单位" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in unitOptions" :key="index" :label="item.key"
                       :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产日期" prop="productDate">
          <el-date-picker v-model="skuData.productDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                          :style="{width: '100%'}" placeholder="请选择生产日期" clearable></el-date-picker>
        </el-form-item>
        <el-form-item label="过期时间" prop="expiredDate">
          <el-date-picker v-model="skuData.expiredDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                          :style="{width: '100%'}" placeholder="请选择过期时间" clearable></el-date-picker>
        </el-form-item>
        <el-form-item label="上架" prop="available">
          <el-switch v-model="skuData.available"></el-switch>
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" @click="submitSKUForm">提交</el-button>
          <el-button @click="resetSKUForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {getCatalog, getStock} from '@/api/store'
  import {getDict} from "@/api/dict";
  import {addProducts, editProducts, addSKU, editSKU, getSKU} from '@/api/product'

  let stocks = [];
  export default {
    name: "productDetail",
    filters: {
      getStock(v) {
        return stocks.map(function (i) {
          return i.id === v ? i.stockName : ""
        })[0]
      },
      format(d) {
        return new Date(d).Format("yyyy-MM-dd")
      }
    },
    data() {
      return {
        title: "添加库存",
        dialogVisible: false,
        skus: [],
        dataList: [],
        addData: {
          productCode: null,
          productName: null,
          keywords: null,
          catalogId: null,
          approvalNumber: null,
          brand: null,
          manufacturer: null,
          prescriptionType: null,
          productmainmaterial: null,
          druginteractions: null,
          precautions: null,
          adverse: null,
          taboo: null,
          outLink: null,
          picture: null,
          isDelete: true,
        },
        addRules: {
          productCode: [{
            required: true,
            message: '请输入产品编码',
            trigger: 'blur'
          }],
          productName: [{
            required: true,
            message: '请输入产品名称',
            trigger: 'blur'
          }],
          keywords: [{
            required: true,
            message: '请输入搜索关键词',
            trigger: 'blur'
          }],
          catalogId: [{
            required: true,
            message: '请选择商品类目',
            trigger: 'change'
          }],
          approvalNumber: [{
            required: true,
            message: '请输入批准文号',
            trigger: 'blur'
          }],
          brand: [{
            required: true,
            message: '请输入品牌',
            trigger: 'blur'
          }],
          manufacturer: [{
            required: true,
            message: '请输入制造商',
            trigger: 'blur'
          }],
          unit: [{
            required: true,
            message: '请输入单位',
            trigger: 'blur'
          }],
          prescriptionType: [{
            required: true,
            message: '请选择处方类型',
            trigger: 'change'
          }],
          productmainmaterial: [],
          druginteractions: [],
          precautions: [],
          adverse: [],
          taboo: [],
          outLink: [],
        },
        pictureAction: 'http://localhost:9403/file/upload',
        picturefileList: [],
        picList: [],
        prescriptionTypeOptions: [],
        unitOptions: [],
        results: {},
        stocks: [],
        skuData: {
          stockId: null,
          batchNo: null,
          supplier: null,
          cost: null,
          num: 0,
          unit: null,
          productDate: null,
          expiredDate: null,
          available:true
        },
        skuRules: {
          stockId: [{
            required: true,
            message: '请输入仓库',
            trigger: 'change'
          }],
          batchNo: [{
            required: true,
            message: '请输入入库批次号',
            trigger: 'blur'
          }],
          supplier: [{
            required: true,
            message: '请输入供应商',
            trigger: 'blur'
          }],
          cost: [{
            required: true,
            message: '请输入含税成本',
            trigger: 'blur'
          }],
          num: [{
            required: true,
            message: '数量',
            trigger: 'blur'
          }],
          unit: [{
            required: true,
            message: '请选择单位',
            trigger: 'change'
          }],
          productDate: [{
            required: true,
            message: '请选择生产日期',
            trigger: 'change'
          }],
          expiredDate: [{
            required: true,
            message: '请选择过期时间',
            trigger: 'change'
          }],
        },
        params: {
          page: 0,
          totalCount: 0,
          totalPage: 1,
          pageSize: 20
        }
      }
    },
    created() {
      window.app = this
      if (this.$route.params.dataList) {
        this.dataList = this.$route.params.dataList;
      } else {
        this.getCatalogs()
      }
      if (this.$route.params.product) {
        this.addData = this.$route.params.product;
        this.skuData.manufacturer = this.addData.manufacturer
      }
      this.getOptions("药品类别").then(result => {
        this.prescriptionTypeOptions = result
      })
      this.getOptions("药品单位").then(result => {
        this.unitOptions = result
      })
      getStock({}).then(response => {
        if (response.code === 200) {
          this.stocks = response.page.list;
          stocks = this.stocks
        }
      })
      if (this.addData.id) {
        this.params.spuId = this.addData.id
        this.searchSKU()
      }

    },
    methods: {
      addSku() {
        this.resetSKUForm()
        this.dialogVisible = true;
        this.title = "新增库存"
      },
      show(row) {
        this.dialogVisible = true;
        this.title = "编辑库存"
        this.skuData = row
      },
      searchSKU(n) {
        if (typeof n === "number") {
          this.params.page = this.params.page + n;
        }
        this.params.spuId = this.addData.id
        getSKU(this.params).then(response => {
          if (response.code === 200) {
            this.skus = response.page.list;
            this.params.page = response.page.currPage;
            this.params.totalPage = response.page.totalPage;
            this.params.totalCount = response.page.totalCount;
          }
        })
      },
      submitSKUForm() {
        this.$refs['skuForm'].validate(valid => {
          if (!valid) return
          // TODO 提交表单
          this.skuData.spuId = this.addData.id
          this.skuData.productCode = this.addData.productCode
          if (this.skuData.id) {
            editSKU(this.skuData).then(response => {
              if (response.code === 200) {
                this.skuData.version++
                this.$message({
                  showClose: true,
                  message: response.msg,
                  type: "success"
                });
                this.dialogVisible = false
              }
            })
          } else {
            this.skuData.manufacturer = this.addData.manufacturer
            addSKU([this.skuData]).then(response => {
              if (response.code === 200) {
                this.$message({
                  showClose: true,
                  message: response.msg,
                  type: "success"
                });
                this.dialogVisible = false
                this.params.page = 0
                this.searchSKU()
              }
            })
          }
        })
      },
      resetSKUForm() {
        this.skuData = {
          stockId: null,
          batchNo: null,
          supplier: null,
          cost: null,
          num: 0,
          unit: null,
          productDate: null,
          expiredDate: null,
          available:true
        }
      },
      saveProduct() {
        this.$refs['addForm'].validate(valid => {
          if (!valid) return
          this.addData.isDelete = this.addData.isDelete ? 0 : 1
          if (this.addData.id) {
            //编辑
            editProducts(this.addData).then(response => {
              if (response.code === 200) {
                this.$message({
                  showClose: true,
                  message: response.msg,
                  type: "success"
                });
                this.addData.version++
              }
            });
          } else {
            //新增
            addProducts(this.addData).then(response => {
              if (response.code === 200) {
                this.$message({
                  showClose: true,
                  message: response.msg,
                  type: "success"
                });
                this.addData.id = response.data.id
              }
            });
          }
        })
      },
      handleRemove(file, fileList) {
        this.picList = this.picList.filter(function (i) {
          return i != file.response.file
        })
        this.addData.picture = JSON.stringify(this.picList)
      },
      handlePictureSuccess(res, f) {
        this.addData.picture = res.file
        this.picList.push(res.file)
        this.addData.picture = JSON.stringify(this.picList)
      },
      pictureBeforeUpload(file) {
        this.$refs.upload.headers.Authorization = this.$store.getters.token
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        let isAccept = new RegExp('image/*').test(file.type)
        if (!isAccept) {
          this.$message.error('应该选择image/*类型的文件')
        }
        return isRightSize && isAccept
      },
      getOptions(key) {
        return getDict({key: key}).then(response => {
          if (response.code === 200) {
            return response.page
          }
        });
      },
      getCatalogs() {
        getCatalog({"pageSize": -1}).then(response => {
          if (response.code === 200) {
            this.dataList = response.page.list
          }
        })
      }
    }
  }
</script>

<style scoped>
  .saveBtn {
    position: fixed;
    top: 66%;
    left: -2%;
    width: 250px;
    margin-left: calc(100% - 250px);
  }
</style>
